<?php
class DebugInterceptor extends Interceptor 
{
    public function before($context) 
    {/*{{{*/
        $debugSql = false;
        if (isset($_GET['debug']))
        {
            BeanFinder::register('clientDebug', new Debugger());
            $debugSql = ('sql' == $_GET['debug']);
        }
        BeanFinder::register('clientDebugSql', $debugSql);
    }/*}}}*/

    public function after($context) 
    {/*{{{*/
        if (isset($_GET['debug']))
        {
            $traces = BeanFinder::get('clientDebug')->getTrace();
            $class = '';
            if (BeanFinder::get('clientDebugSql'))
            {
                $class = ' width="70%" ';
            }
            echo '<table width="100%" border="1" style="text-align:left;"><tr><td>class</td><td>method</td><td>time</td>
                <td>isCached</td><td'.$class.'>sql</td></tr>';
            $getByIdsCnt = $getByIdsTime = $time = $count = 0;
            foreach ($traces as $trace)
            {
                $css = '';
                if ('getByIds' != $trace['method'])
                {
                    if ('no' == $trace['isCached'])
                    {
                        $css = 'style="background-color:red;color:white;"';
                    }
                    echo '<tr><td>'.$trace['class'].'</td><td>'.$trace['method'].'</td><td>'.$trace['time'].'</td><td '.$css.'>'.$trace['isCached'].'</td>
                        <td>'.$this->formatSql($trace['sql']).'</td></tr>';
                    ++$count;
                    $time += $trace['time'];
                }
                else
                {
                    ++$getByIdsCnt;
                    $getByIdsTime += $trace['time'];
                }
            }
            echo '<tr><td colspan="5">共调用:'.($count+$getByIdsCnt).'次(getByIds:'.$getByIdsCnt.', 其它:'.$count.')</td></tr>
                <tr><td colspan="5">共消耗:'.($time+$getByIdsTime).'ms(getByIds:'.$getByIdsTime.', 其它:'.$time.')</td></tr>
                </table>';
        }
    }/*}}}*/

    private function formatSql($sets)
    {
        $str = '';
        if (empty($sets))
        {
            return $str;
        }
        foreach ($sets as $set)
        {
            $str .= "<strong>sql</strong><br>:{$set['sql']}<br><br>";
            $str .= "<strong>explain</strong>:<br>";
            foreach ($set['explain'][0] as $key => $value)
            {
                if ( ('key' == $key && 'NULL' == $value) || ('extra' == $key && strpos($value, 'temporary')))
                {
                    $str .= "<i>$key</i> => <font class='red'><strong>$value</strong></font><br>";
                }
                else
                {
                    $str .= "<i>$key</i> => $value<br>";
                }
            }
        }
        return $str;
    }
}
